import 'dart:io';
import 'package:moonmate/services/database_helper.dart';
import 'package:path_provider/path_provider.dart';

/// 数据同步服务类，负责处理应用中的数据同步和备份恢复功能
class DataSyncService {
  // 使用单例模式
  static final DataSyncService _instance = DataSyncService._internal();
  
  // 初始化数据库助手
  final DatabaseHelper _dbHelper = DatabaseHelper.instance;

  /// 工厂构造函数，确保只创建一个实例
  factory DataSyncService() {
    return _instance;
  }

  /// 私有构造函数
  DataSyncService._internal();

  /// 发送数据变更通知（用于UI更新）
  void notifyDataChanged(String tableName) {
    // 实际应用中可以使用Stream或其他观察者模式来实现
  }

  /// 执行数据同步
  Future<bool> syncData() async {
    try {
      // 在实际应用中，这里会实现与服务器的同步逻辑
      // 但根据需求，我们的应用是完全本地不联网的，所以这里只是一个占位符
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 检查数据一致性
  Future<bool> checkDataConsistency() async {
    try {
      final db = await _dbHelper.database;
      // 检查表是否存在
      final tableNames = [
        DatabaseHelper.tableUser,
        DatabaseHelper.tablePeriod,
        DatabaseHelper.tableSymptom,
        DatabaseHelper.tableBBTRecords,
        DatabaseHelper.tableCMRecords,
        DatabaseHelper.tableOvulationTests,
        DatabaseHelper.tablePregnancy,
        DatabaseHelper.tableBabyInfo,
        DatabaseHelper.tableBabyGrowth,
      ];

      for (final table in tableNames) {
        final result = await db.query(
          'sqlite_master',
          where: 'type = ? AND name = ?',
          whereArgs: ['table', table],
        );
        if (result.isEmpty) {
          return false;
        }
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 创建数据库备份
  Future<String?> createBackup() async {
    try {
      // 获取数据库路径
      final dbPath = await _dbHelper.getDatabasePath();
      final dbFile = File(dbPath);

      if (!dbFile.existsSync()) {
        return null;
      }

      // 创建备份目录
      final externalDir = await getExternalStorageDirectory();
      final backupDir = Directory('${externalDir?.path}/backups');

      if (!backupDir.existsSync()) {
        await backupDir.create(recursive: true);
      }

      // 生成备份文件名（包含时间戳）
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final backupFileName = 'moonmate_backup_$timestamp.db';
      final backupPath = '${backupDir.path}/$backupFileName';

      // 复制数据库文件
      await dbFile.copy(backupPath);

      return backupPath;
    } catch (e) {
      return null;
    }
  }

  /// 从备份恢复数据
  Future<bool> restoreFromBackup(String backupPath) async {
    try {
      final backupFile = File(backupPath);
      
      if (!backupFile.existsSync()) {
        return false;
      }
      
      // 验证备份文件
      if (!await verifyBackup(backupPath)) {
        return false;
      }
      
      // 创建恢复前的临时备份（以防万一）
      final tempBackupPath = await createBackup();
      
      // 关闭当前数据库连接
      await _dbHelper.close();
      
      // 获取数据库路径
      final dbPath = await _dbHelper.getDatabasePath();
      
      // 复制备份文件到数据库位置
      await backupFile.copy(dbPath);
      
      // 重新打开数据库
      await _dbHelper.reopen();
      
      // 验证恢复后的数据
      final isValid = await _dbHelper.transaction((txn) async {
        final result = await txn.query('sqlite_master', where: 'type = ?', whereArgs: ['table']);
        return result.isNotEmpty;
      });
      
      if (isValid) {
        return true;
      } else {
        // 尝试恢复到临时备份
        if (tempBackupPath != null) {
          await restoreFromBackup(tempBackupPath);
        }
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  /// 获取备份列表
  Future<List<File>> getBackupList() async {
    try {
      final externalDir = await getExternalStorageDirectory();
      final backupDir = Directory('${externalDir?.path}/backups');
      
      if (!backupDir.existsSync()) {
        return [];
      }
      
      // 列出所有备份文件并按日期排序
      final files = backupDir.listSync(recursive: false)
          .where((entity) => entity is File && entity.path.endsWith('.db'))
          .map((entity) => entity as File)
          .toList();
      
      // 按修改时间倒序排列（最新的在前面）
      files.sort((a, b) => b.lastModifiedSync().compareTo(a.lastModifiedSync()));
      
      return files;
    } catch (e) {
      return [];
    }
  }

  /// 导出数据为JSON格式（便于用户查看或迁移）
  Future<String?> exportDataAsJson() async {
    try {
      final db = await _dbHelper.database;
      final exportData = <String, dynamic>{
        'export_date': DateTime.now().toIso8601String(),
        'version': '1.0.0',
        'data': <String, List<Map<String, dynamic>>>{}
      };
      
      // 导出核心数据表
      final tablesToExport = [
        DatabaseHelper.tableUser,
        DatabaseHelper.tablePeriod,
        DatabaseHelper.tableSymptom,
        DatabaseHelper.tableBBTRecords,
        DatabaseHelper.tableCMRecords,
        DatabaseHelper.tableOvulationTests,
        DatabaseHelper.tablePregnancy,
        DatabaseHelper.tableBabyInfo,
        DatabaseHelper.tableBabyGrowth
      ];
      
      for (final table in tablesToExport) {
        final data = await db.query(table);
        exportData['data'][table] = data;
      }
      
      // 保存JSON文件
      final externalDir = await getExternalStorageDirectory();
      final exportDir = Directory('${externalDir?.path}/exports');
      
      if (!exportDir.existsSync()) {
        await exportDir.create(recursive: true);
      }
      
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final exportFileName = 'moonmate_export_$timestamp.json';
      final exportPath = '${exportDir.path}/$exportFileName';
      
      final exportFile = File(exportPath);
      await exportFile.writeAsString(_jsonEncode(exportData));
      
      return exportPath;
    } catch (e) {
      return null;
    }
  }

  /// 简单的JSON编码辅助方法（实际应用中应使用jsonEncode）
  String _jsonEncode(dynamic data) {
    if (data is Map) {
      final pairs = data.entries.map((entry) {
        // 对字符串值进行转义
        final valueStr = _jsonEncode(entry.value);
        return '"${entry.key}": $valueStr';
      }).join(', ');
      return '{$pairs}';
    } else if (data is List) {
      final elements = data.map((item) => _jsonEncode(item)).join(', ');
      return '[$elements]';
    } else if (data is String) {
      // 转义特殊字符
      final escaped = data
          .replaceAll('\\', '\\\\')
          .replaceAll('"', '\\"')
          .replaceAll('\n', '\\n')
          .replaceAll('\r', '\\r')
          .replaceAll('\t', '\\t');
      return '"$escaped"';
    } else if (data is bool) {
      return data ? 'true' : 'false';
    } else if (data == null) {
      return 'null';
    } else {
      return data.toString();
    }
  }

  /// 自动备份（可以设置为定期执行）
  Future<void> scheduleAutoBackup({Duration interval = const Duration(days: 7)}) async {
    // 在实际应用中，可以使用后台任务或定时任务来执行自动备份
    // 这里仅作为示例
    
    // 执行备份
    await createBackup();
    
    // 清理旧备份
    await cleanupOldBackups();
    
    // 注意：Flutter中实现真正的后台定时任务需要使用特定的插件
    // 例如：workmanager、flutter_background_fetch等
  }

  /// 获取备份和恢复操作的历史记录
  Future<List<Map<String, dynamic>>> getOperationHistory() async {
    try {
      // 在实际应用中，应该将操作历史存储在数据库中
      // 这里仅作为示例返回空列表
      return [];
    } catch (e) {
      return [];
    }
  }

  /// 验证备份文件的有效性
  Future<bool> verifyBackup(String backupPath) async {
    try {
      final backupFile = File(backupPath);
      
      // 检查文件大小
      if (backupFile.lengthSync() < 1000) { // 最小文件大小检查
        return false;
      }
      
      // 尝试打开文件检查SQLite头部标识
      final bytes = await backupFile.readAsBytes();
      if (bytes.length < 16) return false;
      
      // SQLite文件标识（前16个字节）
      final magicHeader = [0x53, 0x51, 0x4C, 0x69, 0x74, 0x65, 0x20, 0x66, 
                          0x6F, 0x72, 0x6D, 0x61, 0x74, 0x20, 0x33, 0x00];
      
      for (int i = 0; i < magicHeader.length; i++) {
        if (bytes[i] != magicHeader[i]) {
          return false;
        }
      }
      
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 从JSON导入数据
  Future<bool> importDataFromJson(String jsonPath) async {
    try {
      final jsonFile = File(jsonPath);
      
      if (!jsonFile.existsSync()) {
        return false;
      }
      
      // 在真实实现中，这里应该解析JSON并导入数据到数据库
      // 为了演示，这里仅做基本的文件检查
      final fileSize = jsonFile.lengthSync();
      if (fileSize <= 0) {
        return false;
      }
      
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取备份统计信息
  Future<Map<String, dynamic>> getBackupStatistics() async {
    try {
      final backups = await getBackupList();
      
      if (backups.isEmpty) {
        return {
          'total_count': 0,
          'latest_backup': null,
          'total_size': 0
        };
      }
      
      final totalSize = backups.fold<int>(0, (sum, file) => sum + file.lengthSync());
      final latestBackup = backups.first;
      
      return {
        'total_count': backups.length,
        'latest_backup': {
          'path': latestBackup.path,
          'size': latestBackup.lengthSync(),
          'date': latestBackup.lastModifiedSync()
        },
        'total_size': totalSize
      };
    } catch (e) {
      return {'total_count': 0, 'latest_backup': null, 'total_size': 0};
    }
  }

  /// 清理旧备份（保留最新的N个）
  Future<void> cleanupOldBackups({int keepCount = 5}) async {
    try {
      final backups = await getBackupList();
      
      if (backups.length <= keepCount) {
        return; // 不需要清理
      }
      
      // 删除旧的备份
      for (int i = keepCount; i < backups.length; i++) {
        await backups[i].delete();
      }
    } catch (e) {
      // 错误处理
    }
  }
}

/// 数据备份服务类，专注于数据的备份和恢复功能
class DataBackupService {
  static final DataBackupService _instance = DataBackupService._internal();

  factory DataBackupService() {
    return _instance;
  }

  DataBackupService._internal();

  /// 创建完整备份
  Future<String?> createFullBackup() async {
    final syncService = DataSyncService();
    return await syncService.createBackup();
  }

  /// 恢复完整备份
  Future<bool> restoreFullBackup(String backupPath) async {
    final syncService = DataSyncService();
    return await syncService.restoreFromBackup(backupPath);
  }

  /// 获取备份列表
  Future<List<File>> getBackups() async {
    final syncService = DataSyncService();
    return await syncService.getBackupList();
  }

  /// 验证备份文件
  Future<bool> validateBackup(String backupPath) async {
    final syncService = DataSyncService();
    return await syncService.verifyBackup(backupPath);
  }

  /// 清理旧备份
  Future<void> cleanupOldBackups({int keepCount = 5}) async {
    final syncService = DataSyncService();
    await syncService.cleanupOldBackups(keepCount: keepCount);
  }
}

/// 数据状态管理类，负责跟踪应用的数据状态
class DataStateManager {
  static final DataStateManager _instance = DataStateManager._internal();
  bool _isDataLoaded = false;
  bool _isSyncing = false;
  final Map<String, bool> _tableStatus = {};

  factory DataStateManager() {
    return _instance;
  }

  DataStateManager._internal();

  /// 标记数据已加载
  void markDataLoaded() {
    _isDataLoaded = true;
  }

  /// 标记数据加载中
  void markDataLoading() {
    _isDataLoaded = false;
  }

  /// 检查数据是否已加载
  bool isDataLoaded() {
    return _isDataLoaded;
  }

  /// 标记同步开始
  void startSync() {
    _isSyncing = true;
  }

  /// 标记同步结束
  void endSync() {
    _isSyncing = false;
  }

  /// 检查是否正在同步
  bool isSyncing() {
    return _isSyncing;
  }

  /// 更新表状态
  void updateTableStatus(String tableName, bool isUpToDate) {
    _tableStatus[tableName] = isUpToDate;
  }

  /// 检查表状态
  bool isTableUpToDate(String tableName) {
    return _tableStatus[tableName] ?? true;
  }

  /// 重置所有表状态
  void resetTableStatus() {
    _tableStatus.clear();
  }
}